﻿Ext.define('Html5App.controller.CustomerController', {
	extend : 'Ext.app.Controller',
	config : {
		models : [],
		views : [],
		refs : {
			customerSelect : 'customerSelect',
			customerInfo : 'customerInfo',
			customerOptions : 'customerOptions',
			brandProgress : 'brandProgress',
			salesProgress : 'salesProgress',
			callCardRecord : 'callCardRecord',
			orderRecord : 'orderRecord',
			customerSelectAddress : 'customerSelectAddress',
			customerNewOrder : 'customerNewOrder',
			newOrderSelectBrand : 'newOrderSelectBrand',
			newOrderSelectSort : 'newOrderSelectSort',
			newOrderSelectType : 'newOrderSelectType',
			newOrderSelectProduct : 'newOrderSelectProduct',
			newOrderSelectProductInfo : 'newOrderSelectProductInfo',
			findCustomerByArea : 'button[action=findCustomerByArea]',
			selectCustomerOptions : 'button[action=selectCustomerOptions]',
			customerAddOrder : 'button[action=customerAddOrder]',
			confirmBuy : 'button[action=confirmBuy]',
			selectBrand : 'button[action=selectBrand]',
			selectCancel : 'button[action=selectCancel]',
			brandTap : 'button[action=brandTap]',
			sortTap : 'button[action=sortTap]',
			typeTap : 'button[action=typeTap]',
			productTap : 'button[action=productTap]',
			confirmButton : 'button[action=confirmButton]',
			customerUpdateOrder : 'button[action=customerUpdateOrder]',
			customerDeleteOrder : 'button[action=customerDeleteOrder]',
			orderSettleAction : 'button[action=orderSettleAction]'
		},
		control : {
			customerSelect : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					util.showLoadMask(null);
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql(
				            	"select * from LastSelectArea",
				            	[],
				            	function (tx, result) {
				            		if(Number(result.rows.length) > 0){
				            			var obj = result.rows.item(0);
				            			config.last_area_code = obj['CodeTerr'];
				            			config.last_area_code_name = obj['CodeNameTerr'];
				            		}
				            	},
				            	function (tx, error) {}
				            );
				        	tx.executeSql(
				        			"select * from LastSelectCustomer",
				        			[],
				        			function (tx, result) {
				        				if(Number(result.rows.length) > 0){
				        					var obj = result.rows.item(0);
				        					config.last_customer_code = obj['CustomerCode'];
				        				}
				        			},
				        			function (tx, error) {}
				        	);
				        	tx.executeSql(
				        		"select * from Area where SalesCode='"+config.current_user.user_name+"'", 
				        		[],
				        		function (tx, r) {
				        			util.hideLoadMask();
				        			if(Number(r.rows.length) > 0){
				        				config.area_arr = [];
		                        		var j = 0;
		                        		for(var i=0;i<r.rows.length;i++){
		                        			var areaObj = r.rows.item(i);
		                        			if(areaObj.CodeTerr!=null && areaObj.CodeTerr!='' && areaObj.NameTerr!=null && areaObj.NameTerr!=''){
		                        				var CodeTerr = areaObj.CodeTerr;
			                        			config.area_arr.push(CodeTerr);
			                        			var buttonLabel = CodeTerr+" "+areaObj.NameTerr;
			                        			if(config.last_area_code == null || config.last_area_code == ""){
			                        				config.last_area_code = CodeTerr;
			                        				config.last_area_code_name = buttonLabel;
			                        			}
			                        			Ext.getCmp('customer-select-area').add(
													{
														xtype : 'button',
														cls : 'customer-select-area-button',
														style : CodeTerr == config.last_area_code ? 'background-color:#FCC304;color: #FFFFFF;' : '',
														action : 'findCustomerByArea',
														id : "area_button_"+CodeTerr,
														html : buttonLabel
													}
												);
			                        			j++;
		                        			}
		                        		}
		                        		config.area_code = config.last_area_code_name;
	                        			Ext.getCmp("customer-select-object").removeAll();
										var CodeTerrStr = config.last_area_code;
										util.showLoadMask(null);
										tx.executeSql(
							        		"select * from Customer where SalesCode='"+config.current_user.user_name+"' and CodeTerr='"+CodeTerrStr+"'", 
							        		[],
							        		function (tx, r) {
							        			util.hideLoadMask();
							        			if(Number(r.rows.length) > 0){
							        				Ext.getCmp("customer-select-number").setHtml("&nbsp;客戶"+r.rows.length+"個");
							        				for(var k=0;k<r.rows.length;k++){
					                        			if(k<Number(Number(r.rows.length)-1)){
					                        				var customerObj1 = r.rows.item(k);
					                        				var customerObj2 = r.rows.item(k+1);
					                        				var customerObj1Code = "customer_button_"+customerObj1.CustomerCode+"_"+customerObj1.SalesCode;
					                        				var customerObj2Code = "customer_button_"+customerObj2.CustomerCode+"_"+customerObj2.SalesCode;
					                        				Ext.getCmp("customer-select-object").add(
						                        				{
						                        					xtype : 'container',
						                        					cls : 'customer-select-customer-info',
						                        					layout : {
																		type : 'hbox'
																	},
																	items : [{
																		flex : 1,
																		cls : customerObj1Code == config.last_customer_code ? 'customer-select-customer-button-select' : 'customer-select-customer-button',
																		id : "customer_button_"+customerObj1.CustomerCode+"_"+customerObj1.SalesCode,
																		html : customerObj1.CustomerCode+"<br/>"+customerObj1.CustomerName,
																		listeners : {
																			element : 'element',
																			singletap : function() {
																				config.customer_code = this.id;
																				Ext.getCmp("customerHome").removeAll();
																				Ext.getCmp("customerHome").add({
																					xtype : 'customerInfo'
																				});
																				config.database.transaction(
																					function (txc) {
																						//清空LastSelectCustomer表
																						txc.executeSql("delete from LastSelectCustomer",
																							[],
																							function (txc, r) {},
																							function (txc, e) {}
																						);
												                        				//写入LastSelectCustomer表
												                        				txc.executeSql("insert into LastSelectCustomer(CustomerCode) values ('"+config.customer_code+"')",
																							[],
																							function (txc, r) {
																								
																							},
																							function (txc, e) {}
																						);
																					}
																				);
																			}
																		}
																	},{
																		cls : 'customer-select-line'
																	},{
																		flex : 1,
																		cls : customerObj2Code == config.last_customer_code ? 'customer-select-customer-button-select' : 'customer-select-customer-button',
																		id : "customer_button_"+customerObj2.CustomerCode+"_"+customerObj2.SalesCode,
																		html : customerObj2.CustomerCode+"<br/>"+customerObj2.CustomerName,
																		listeners : {
																			element : 'element',
																			singletap : function() {
																				config.customer_code = this.id;
																				Ext.getCmp("customerHome").removeAll();
																				Ext.getCmp("customerHome").add({
																					xtype : 'customerInfo'
																				});
																				config.database.transaction(
																					function (txc) {
																						//清空LastSelectCustomer表
																						txc.executeSql("delete from LastSelectCustomer",
																							[],
																							function (txc, r) {},
																							function (txc, e) {}
																						);
												                        				//写入LastSelectCustomer表
												                        				txc.executeSql("insert into LastSelectCustomer(CustomerCode) values ('"+config.customer_code+"')",
																							[],
																							function (txc, r) {
																								
																							},
																							function (txc, e) {}
																						);
																					}
																				);
																			}
																		}
																	}]
						                        				}
						                        			);
					                        				k++;
					                        			}else{
					                        				var customerObj = r.rows.item(k);
					                        				var customerObjCode = "customer_button_"+customerObj.CustomerCode+"_"+customerObj.SalesCode;
					                        				Ext.getCmp("customer-select-object").add(
						                        				{
						                        					xtype : 'container',
						                        					cls : 'customer-select-customer-info',
						                        					layout : {
																		type : 'hbox'
																	},
																	items : [{
																		flex : 1,
																		cls : customerObjCode == config.last_customer_code ? 'customer-select-customer-button-select' : 'customer-select-customer-button',
																		id : "customer_button_"+customerObj.CustomerCode+"_"+customerObj.SalesCode,
																		html : customerObj.CustomerCode+"<br/>"+customerObj.CustomerName,
																		listeners : {
																			element : 'element',
																			singletap : function() {
																				config.customer_code = this.id;
																				Ext.getCmp("customerHome").removeAll();
																				Ext.getCmp("customerHome").add({
																					xtype : 'customerInfo'
																				});
																				config.database.transaction(
																					function (txc) {
																						//清空LastSelectCustomer表
																						txc.executeSql("delete from LastSelectCustomer",
																							[],
																							function (txc, r) {},
																							function (txc, e) {}
																						);
												                        				//写入LastSelectCustomer表
												                        				txc.executeSql("insert into LastSelectCustomer(CustomerCode) values ('"+config.customer_code+"')",
																							[],
																							function (txc, r) {
																								
																							},
																							function (txc, e) {}
																						);
																					}
																				);
																			}
																		}
																	},{
																		cls : 'customer-select-line'
																	},{
																		flex : 1,
																		cls : 'customer-select-customer-button',
																		html : ""
																	}]
						                        				}
						                        			);
					                        			}
					                        		}
							        				
							        			}
							        		},
							        		function (tx, e) {
							        			util.hideLoadMask();
							        		}
							            );
				        			}
				        		},
				        		function (tx, e) {
				        			util.hideLoadMask();
				        		}
				            );
				        }
				    );
				}
			},
			findCustomerByArea : {
				tap : function(button, e, eOpts) {
					for(var i=0;i<config.area_arr.length;i++){
						var buttonId = 'area_button_'+config.area_arr[i];
						Ext.getCmp(buttonId).setStyle("background-color:transparent;color: #4C4C4C;");
					}
					button.setStyle("background-color:#FCC304;color: #FFFFFF;");
					var buttonLabel = button.getHtml();
					config.area_code = buttonLabel;
					Ext.getCmp("customer-select-object").removeAll();
					var CodeTerrStr = button.getId().replace("area_button_","");
					config.database.transaction(
						function (txc) {
							//清空LastSelectArea表
							txc.executeSql("delete from LastSelectArea",
								[],
								function (txc, r) {},
								function (txc, e) {}
							);
            				//写入LastSelectArea表
            				txc.executeSql("insert into LastSelectArea(CodeTerr,CodeNameTerr) values ('"+CodeTerrStr+"','"+config.area_code+"')",
								[],
								function (txc, r) {
									
								},
								function (txc, e) {}
							);
						}
					);
					util.showLoadMask(null);
					config.database.transaction(
				        function (tx) {
							tx.executeSql(
				        		"select * from Customer where SalesCode='"+config.current_user.user_name+"' and CodeTerr='"+CodeTerrStr+"'", 
				        		[],
				        		function (tx, r) {
				        			util.hideLoadMask();
				        			if(Number(r.rows.length) > 0){
				        				Ext.getCmp("customer-select-number").setHtml("&nbsp;客戶"+r.rows.length+"個");
				        				for(var k=0;k<r.rows.length;k++){
		                        			if(k<Number(Number(r.rows.length)-1)){
		                        				var customerObj1 = r.rows.item(k);
		                        				var customerObj2 = r.rows.item(k+1);
		                        				var customerObj1Code = "customer_button_"+customerObj1.CustomerCode+"_"+customerObj1.SalesCode;
		                        				var customerObj2Code = "customer_button_"+customerObj2.CustomerCode+"_"+customerObj2.SalesCode;
		                        				Ext.getCmp("customer-select-object").add(
			                        				{
			                        					xtype : 'container',
			                        					cls : 'customer-select-customer-info',
			                        					layout : {
															type : 'hbox'
														},
														items : [{
															flex : 1,
															cls : customerObj1Code == config.last_customer_code ? 'customer-select-customer-button-select' : 'customer-select-customer-button',
															id : "customer_button_"+customerObj1.CustomerCode+"_"+customerObj1.SalesCode,
															html : customerObj1.CustomerCode+"<br/>"+customerObj1.CustomerName,
															listeners : {
																element : 'element',
																singletap : function() {
																	config.customer_code = this.id;
																	Ext.getCmp("customerHome").removeAll();
																	Ext.getCmp("customerHome").add({
																		xtype : 'customerInfo'
																	});
																	config.database.transaction(
																		function (txc) {
																			//清空LastSelectCustomer表
																			txc.executeSql("delete from LastSelectCustomer",
																				[],
																				function (txc, r) {},
																				function (txc, e) {}
																			);
									                        				//写入LastSelectCustomer表
									                        				txc.executeSql("insert into LastSelectCustomer(CustomerCode) values ('"+config.customer_code+"')",
																				[],
																				function (txc, r) {
																					
																				},
																				function (txc, e) {}
																			);
																		}
																	);
																}
															}
														},{
															cls : 'customer-select-line'
														},{
															flex : 1,
															cls : customerObj2Code == config.last_customer_code ? 'customer-select-customer-button-select' : 'customer-select-customer-button',
															id : "customer_button_"+customerObj2.CustomerCode+"_"+customerObj2.SalesCode,
															html : customerObj2.CustomerCode+"<br/>"+customerObj2.CustomerName,
															listeners : {
																element : 'element',
																singletap : function() {
																	config.customer_code = this.id;
																	Ext.getCmp("customerHome").removeAll();
																	Ext.getCmp("customerHome").add({
																		xtype : 'customerInfo'
																	});
																	config.database.transaction(
																		function (txc) {
																			//清空LastSelectCustomer表
																			txc.executeSql("delete from LastSelectCustomer",
																				[],
																				function (txc, r) {},
																				function (txc, e) {}
																			);
									                        				//写入LastSelectCustomer表
									                        				txc.executeSql("insert into LastSelectCustomer(CustomerCode) values ('"+config.customer_code+"')",
																				[],
																				function (txc, r) {
																					
																				},
																				function (txc, e) {}
																			);
																		}
																	);
																}
															}
														}]
			                        				}
			                        			);
		                        				k++;
		                        			}else{
		                        				var customerObj = r.rows.item(k);
		                        				var customerObjCode = "customer_button_"+customerObj.CustomerCode+"_"+customerObj.SalesCode;
		                        				Ext.getCmp("customer-select-object").add(
			                        				{
			                        					xtype : 'container',
			                        					cls : 'customer-select-customer-info',
			                        					layout : {
															type : 'hbox'
														},
														items : [{
															flex : 1,
															cls : customerObjCode == config.last_customer_code ? 'customer-select-customer-button-select' : 'customer-select-customer-button',
															id : "customer_button_"+customerObj.CustomerCode+"_"+customerObj.SalesCode,
															html : customerObj.CustomerCode+"<br/>"+customerObj.CustomerName,
															listeners : {
																element : 'element',
																singletap : function() {
																	config.customer_code = this.id;
																	Ext.getCmp("customerHome").removeAll();
																	Ext.getCmp("customerHome").add({
																		xtype : 'customerInfo'
																	});
																	config.database.transaction(
																		function (txc) {
																			//清空LastSelectCustomer表
																			txc.executeSql("delete from LastSelectCustomer",
																				[],
																				function (txc, r) {},
																				function (txc, e) {}
																			);
									                        				//写入LastSelectCustomer表
									                        				txc.executeSql("insert into LastSelectCustomer(CustomerCode) values ('"+config.customer_code+"')",
																				[],
																				function (txc, r) {
																					
																				},
																				function (txc, e) {}
																			);
																		}
																	);
																}
															}
														},{
															cls : 'customer-select-line'
														},{
															flex : 1,
															cls : 'customer-select-customer-button',
															html : ""
														}]
			                        				}
			                        			);
		                        			}
		                        		}
				        				
				        			}
				        		},
				        		function (tx, e) {
				        			util.hideLoadMask();
				        		}
				            );
				        }
				    );
				}
			},
			customerInfo : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					var CustomerCode = config.customer_code.replace("customer_button_","").split("_")[0];
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql(
				        		"select * from Customer where CustomerCode='"+CustomerCode+"' and SalesCode='"+config.current_user.user_name+"'", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				var customerObj = r.rows.item(0);
				        				Ext.getCmp("customer-info-name").setHtml(customerObj["CustomerCode"]+" "+customerObj["CustomerName"]);
		                        		Ext.getCmp("customer-info-name-ctac").setHtml(customerObj["NameCtac"]);
		                        		Ext.getCmp("customer-info-code-terr").setHtml(config.area_code);
		                        		Ext.getCmp("customer-info-phone").setHtml(customerObj["Phone"]);
		                        		Ext.getCmp("customer-info-fax").setHtml(customerObj["Fax"]);
		                        		Ext.getCmp("customer-info-text-desc").setHtml(customerObj["TextDesc"]);
		                        		Ext.getCmp("customer-info-address").setHtml(customerObj["Address1"]+";"+customerObj["Address2"]+";"+customerObj["Address3"]);
		                        		if(customerObj["AMTCRLIMT"] && Number(customerObj["AMTCRLIMT"])>0){
		                        			Ext.getCmp("customer-info-amtcrlimt").setHtml("$"+custom.thousandBitSeparator(customerObj["AMTCRLIMT"],0));
		                        			config.customer_amtcrlimt = Number(customerObj["AMTCRLIMT"]);
		                        		}else{
		                        			Ext.getCmp("customer-info-amtcrlimt").setHtml("$"+"0.00");
		                        			config.customer_amtcrlimt = 0;
		                        		}
		                        		if(customerObj["AllInvAmt"] && Number(customerObj["AllInvAmt"])>0){
		                        			Ext.getCmp("customer-info-allinvamt").setHtml("$"+custom.thousandBitSeparator(customerObj["AllInvAmt"],0));
		                        		}else{
		                        			Ext.getCmp("customer-info-allinvamt").setHtml("$"+"0.00");
		                        		}
		                        		if(customerObj["Balance"] && Number(customerObj["Balance"])>0){
		                        			Ext.getCmp("customer-info-balance").setHtml("$"+custom.thousandBitSeparator(customerObj["Balance"],0));
		                        			config.customer_balance = Number(customerObj["Balance"]);
		                        		}else{
		                        			Ext.getCmp("customer-info-balance").setHtml("$"+"0.00");
		                        			config.customer_balance = 0;
		                        		}
		                        		if(customerObj["T1"] && Number(customerObj["T1"])>0){
		                        			Ext.getCmp("customer-info-t1").setHtml("$"+custom.thousandBitSeparator(customerObj["T1"],0));
		                        		}else{
		                        			Ext.getCmp("customer-info-t1").setHtml("$"+"0.00");
		                        		}
		                        		Ext.getCmp("customer-info-note").setHtml(customerObj["Note"]);
				        			}
				        		},
				        		function (tx, e) {}
				            );
				            tx.executeSql(
				        		"select sum(OrderAmt) as actual from TAllSalesDataPK where CUSTOMER='"+CustomerCode+"' and SRCode='"+config.current_user.user_name+"' and ORDDATE>='"+custom.getCurrentMonthFirst()+"' and ORDDATE<='"+custom.getCurrentMonthLast()+"' group by CUSTOMER", 
				        		[],
				        		function (tx, r) {
				        			Ext.getCmp("customer-info-actual").setHtml("$"+"0.00");
				        			if(Number(r.rows.length) > 0){
				        				var customerObj = r.rows.item(0);
		                        		if(customerObj["actual"] && Number(customerObj["actual"])>0){
		                        			Ext.getCmp("customer-info-actual").setHtml("$"+custom.thousandBitSeparator(customerObj["actual"],0));
		                        		}
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
				}
			},
			selectCustomerOptions : {
				tap : function(button, e, eOpts) {
					for(var i=1;i<=5;i++){
						var buttonId = 'customer-options'+i;
						Ext.getCmp(buttonId).setStyle("color:#FFFFFF;background-image:none;");
					}
					button.setStyle("color:#FCC304;background-image:url(./resources/images/checked.png);");
					config.customer_options = button.getId().replace("customer-options","");
					button.parent.parent.destroy();
					if(config.customer_options == 1){
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'customerInfo'
						});
					}else if(config.customer_options == 2){
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'brandProgress'
						});
					}else if(config.customer_options == 3){
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'salesProgress'
						});
					}else if(config.customer_options == 4){
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'callCardRecord'
						});
					}else if(config.customer_options == 5){
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'orderRecord'
						});
					}
				}
			},
			customerOptions : {
				show : function( t, eOpts ) {
					for(var i=1;i<=5;i++){
						var buttonId = 'customer-options'+i;
						Ext.getCmp(buttonId).setStyle("color:#FFFFFF;background-image:none;");
					}
					Ext.getCmp("customer-options"+config.customer_options).setStyle("color:#FCC304;background-image:url(./resources/images/checked.png);");
				}
			},
			brandProgress : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					util.showLoadMask(null);
					var CustomerCode = config.customer_code.replace("customer_button_","").split("_")[0];
					var customerObj,brandProgressList,brandProgressDetailList;
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql(
				        		"select * from Customer where CustomerCode='"+CustomerCode+"' and SalesCode='"+config.current_user.user_name+"'", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				customerObj = r.rows.item(0);
				        			}
				        		},
				        		function (tx, e) {}
				            );
				            tx.executeSql(
			        			" select tmp.BrandCode, sum(tmp.Target1 * 1000) as Target, sum(tmp.Actual) as Actual,"+
							  	" CASE WHEN sum(tmp.Target1*1000)<=0 THEN 100 ELSE sum(tmp.Actual)/sum(tmp.Target1*1000)*100 END as exponential,"+
								" CASE WHEN sum(tmp.Target1*1000)<=sum(tmp.Actual) THEN 0 ELSE sum(tmp.Target1*1000)-sum(tmp.Actual) END as owe,"+
							  	" sum(tmp.CustomerNum) as Custs "+
								" from ( "+
									 " select a.BrandCode, sum(a.Target) as Target1, 0 as Actual, 0 as CustomerNum "+
									 " from CustomerBrandTarget a, Customer b "+
									 " where a.CustomerCode = b.CustomerCode and a.SalesCode = b.SalesCode and b.CustomerCode = '"+CustomerCode+"' and b.SalesCode = '"+config.current_user.user_name+"'"+
									 " group by a.BrandCode"+
									 " union all "+
									 " select a.CNTLACCT as BrandCode, 0 as Target1, sum(a.OrderAmt) as Actual, 0 as CustomerNum  "+
									 " from TAllSalesDataPK a, Customer b "+
									 " where a.Customer = b.CustomerCode and a.SRCode = b.SalesCode "+
									 " and a.ORDDATE >= '"+custom.getCurrentMonthFirst()+"'"+
									 " And a.ORDDATE <= '"+custom.getCurrentMonthLast()+"' "+
									 " and b.CustomerCode = '"+CustomerCode+"' "+
									 " and b.SalesCode = '"+config.current_user.user_name+"'"+
									 " group by a.CNTLACCT "+
									 " union all "+
									 " select custtmp.BrandCode, 0 as Target1, 0 as Actual, Count(custtmp.Customer) as CustomerNum "+
									 " from ( "+
									 " select a.CNTLACCT as BrandCode, a.Customer  "+
									 " from TAllSalesDataPK a, Customer b "+
									 " where a.Customer = b.CustomerCode and a.SRCode = b.SalesCode "+
									 " and a.ORDDATE >= '"+custom.getCurrentMonthFirst()+"'"+
									 " And a.ORDDATE <= '"+custom.getCurrentMonthLast()+"'"+
									 " and b.CustomerCode = '"+CustomerCode+"' "+ 
									 " and b.SalesCode = '"+config.current_user.user_name+"'"+
									 " group by a.CNTLACCT, a.Customer"+
									 " ) custtmp group by custtmp.BrandCode "+
									" ) tmp, "+
									" (select b.BrandName "+
									" from Item a left join Brand b on a.BrandID = b.BrandCode "+
									" group by b.BrandName"+
								" ) tmp1 "+
								" where tmp.BrandCode = tmp1.BrandName "+
								" group by tmp.BrandCode "+
								" order by tmp.BrandCode", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				brandProgressList = r.rows;
				        			}
				        		},
				        		function (tx, e) {}
				            );
				          	tx.executeSql(
				        		"select tmp.BrandCode, tmp.Item, tmp.UNIT, tmp.Description, "+
								  	" Round(sum(tmp.Amt)/sum(tmp.Qty),2) unitPrice,"+
								  	" sum(tmp.Qty) as SalesQty, sum(tmp.Amt) as Amount "+
									" from ( "+
									 " select a.CNTLACCT as BrandCode, a.Item, max(a.ORDUNIT) as UNIT, Max(a.[DESC]) as Description, sum(a.OCTN + a.OPC) as Qty, sum(a.OrderAmt) as Amt "+
									 " from TAllSalesDataPK a, Customer b "+
									 " where a.Customer = b.CustomerCode and a.SRCode = b.SalesCode "+
									 " and a.ORDDATE >= '"+custom.getCurrentMonthFirst()+"'"+
									 " and a.ORDDATE <= '"+custom.getCurrentMonthLast()+"'"+
									 " and b.CustomerCode = '"+CustomerCode+"' "+
									 " and b.SalesCode = '"+config.current_user.user_name+"'"+
									 " group by a.CNTLACCT, a.Item) tmp "+
									" group by tmp.BrandCode, tmp.Item, tmp.UNIT, tmp.Description "+
									" order by tmp.BrandCode, tmp.Item", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				brandProgressDetailList = r.rows;
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
				    setTimeout(function dataShow(){
				    	Ext.getCmp("brand-progress-customer-name").setHtml(customerObj["CustomerCode"]+" "+customerObj["CustomerName"]);
        				var htmlStr = "";
        				var sumHtmlStr = "";
        				Ext.getCmp("brand-progress-data").setHtml(htmlStr);
            			Ext.getCmp("brand-progress-data-sum").setHtml(sumHtmlStr);
        				sumHtmlStr += '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border-top:1px solid #CFCFCF;border-bottom:1px solid #CFCFCF;font-size:0.7rem;color:#4C4C4C;">';
        				htmlStr += '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="border-top:1px solid #CFCFCF;border-bottom:1px solid #CFCFCF;font-size:0.7rem;color:#4C4C4C;margin-top: -1px;">';
						config.brand_code_arr = [];
						var targetTotal=0,actualTotal=0,exponentialTotal=0,oweTotal=0;
						if(brandProgressList && Number(brandProgressList.length)>0){
							for(var i=0;i<brandProgressList.length;i++){
		            			var brandProgress = brandProgressList.item(i);
		            			targetTotal=Number(Number(targetTotal)+Number(brandProgress["Target"]));
                    			actualTotal=Number(Number(actualTotal)+Number(brandProgress["Actual"]));
		            			config.brand_code_arr.push(brandProgress["BrandCode"]);
		            			if(i%2==0){
		            				 htmlStr += '<tr style="height:2rem;background-color:#F5F5F5;" onclick="javascript:custom.brandProgressToView(\''+brandProgress["BrandCode"]+'\');">';
		            			} else {
		            				 htmlStr += '<tr style="height:2rem;background-color:#FFFFFF;" onclick="javascript:custom.brandProgressToView(\''+brandProgress["BrandCode"]+'\');">';
		            			}
									  	htmlStr += ''+
												    '<td style="border-right:1px solid #CFCFCF;text-align:center;width:10%;"><img style="width:1.5rem;height:auto;" src="'+cordova.file.dataDirectory +'/Logo/Brand/'+brandProgress["BrandCode"]+'.JPG"/></td>'+
												    '<td style="border-right:1px solid #CFCFCF;padding-left:0.1rem;width:30%;">'+brandProgress["BrandCode"]+'</td>'+
												    '<td style="border-right:1px solid #CFCFCF;padding-right:0.2rem;text-align:right;width:17%;">'+custom.thousandBitSeparator(brandProgress["Target"],0)+'</td>'+
												    '<td style="border-right:1px solid #CFCFCF;padding-right:0.2rem;text-align:right;width:17%;">'+custom.thousandBitSeparator(brandProgress["Actual"],0)+'</td>'+
												    '<td style="border-right:1px solid #CFCFCF;padding-right:0.2rem;text-align:right;width:11%;">'+brandProgress["exponential"]+'</td>'+
												    '<td style="padding-right:0.2rem;text-align:right;width:15%;">'+brandProgress["owe"]+'</td>'+
												  '</tr>'+
												  '<tr style="display:none;" id="'+brandProgress["BrandCode"]+'_Detail">'+
												  	'<td colspan="6">'+
												        '<table width="100%" border="0" cellpadding="0" cellspacing="0" style="color:#4D4D4D;">'+
												          '<tr style="height:1.6rem;background-color:#E1E1E1;font-weight:bold;text-align:center;">'+
												            '<td style="border-right:1px solid #CFCFCF;width:40%;">貨品</td>'+
												            '<td style="border-right:1px solid #CFCFCF;width:17%;">單位</td>'+
												            '<td style="border-right:1px solid #CFCFCF;width:17%;">單價</td>'+
												            '<td style="border-right:1px solid #CFCFCF;width:11%;">數量</td>'+
												            '<td style="width:15%;">總額</td>'+
												          '</tr>';
								   if(brandProgressDetailList && Number(brandProgressDetailList.length)>0){
								   		for(var j=0;j<brandProgressDetailList.length;j++){
								              var brandProgressDetail = brandProgressDetailList.item(j);
								              if(brandProgress["BrandCode"]==brandProgressDetail["BrandCode"]){
									              		htmlStr +='<tr style="height:1.6rem;background-color:#E1E1E1;">'+
														            '<td style="border-right:1px solid #CFCFCF;padding-left:0.1rem;">'+brandProgressDetail["Description"]+'</td>'+
														            '<td style="border-right:1px solid #CFCFCF;padding-left:0.1rem;text-align:center;">'+brandProgressDetail["UNIT"]+'</td>'+
														            '<td style="border-right:1px solid #CFCFCF;padding-right:0.2rem;text-align:right;">'+custom.thousandBitSeparator(brandProgressDetail["unitPrice"],2)+'</td>'+
														            '<td style="border-right:1px solid #CFCFCF;padding-right:0.2rem;text-align:right;">'+custom.thousandBitSeparator(brandProgressDetail["SalesQty"],0)+'</td>'+
														            '<td style="padding-right:0.2rem;text-align:right;">'+custom.thousandBitSeparator(brandProgressDetail["Amount"],0)+'</td>'+
														          '</tr>';
								              }
								          }
								   }
						        htmlStr += '</table>'+
										'</td>'+
									  '</tr>';
		            		}
							if(Number(targetTotal)<=0){
	                			exponentialTotal = 100;
	                		}else{
	                			exponentialTotal = Number(Number(actualTotal/targetTotal)*100).toFixed(2);
	                		}
	                		oweTotal = Number(targetTotal) - Number(actualTotal);
	                		if(Number(oweTotal)<=0){
	                			oweTotal = 0;
	                		}
	                		sumHtmlStr +=   '<tr style="height:2rem;background-color:#FFFFFF;font-weight:bold;border-top:1px solid #CFCFCF;">'+
											    '<td style="border-right:1px solid #CFCFCF;width:40%;padding-left:0.1rem;">總計</td>'+
											    '<td style="border-right:1px solid #CFCFCF;width:17%;padding-right:0.2rem;text-align:right;">'+custom.thousandBitSeparator(targetTotal,0)+'</td>'+
											    '<td style="border-right:1px solid #CFCFCF;width:17%;padding-right:0.2rem;text-align:right;">'+custom.thousandBitSeparator(actualTotal,0)+'</td>'+
											    '<td style="border-right:1px solid #CFCFCF;width:11%;padding-right:0.2rem;text-align:right;">'+exponentialTotal+'</td>'+
											    '<td style="border-right:1px solid #CFCFCF;width:15%;padding-right:0.2rem;text-align:right;">'+oweTotal+'</td>'+
										    '</tr>';
						}
	            		htmlStr += '</table>';
						Ext.getCmp("brand-progress-data").setHtml(htmlStr);
						sumHtmlStr += '</table>';
						Ext.getCmp("brand-progress-data-sum").setHtml(sumHtmlStr);
						util.hideLoadMask();
				    }, 1500);
				}
			},
			salesProgress : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					var now = new Date();
					var curDate = '';
					var curMonth = parseInt(now.getMonth()+1);
				    curDate += now.getFullYear();
				    curDate += '-';
					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
					curDate += '-';
					curDate += now.getDate() < 10 ? '0'+now.getDate() : now.getDate();
					Ext.getCmp("salesProgressBeginDate").getComponent('field-value').setHtml(curDate.substr(0,8)+"01");
					Ext.getCmp("salesProgressBeginDate").getComponent('field-value').setData(curDate.substr(0,8)+"01");
					Ext.getCmp("salesProgressEndDate").getComponent('field-value').setHtml(curDate);
					Ext.getCmp("salesProgressEndDate").getComponent('field-value').setData(curDate);
					Ext.getCmp("salesProgressBeginMonth").getComponent('field-value').setHtml(curDate.substr(0,7));
					Ext.getCmp("salesProgressBeginMonth").getComponent('field-value').setData(curDate.substr(0,7));
					Ext.getCmp("salesProgressEndMonth").getComponent('field-value').setHtml(curDate.substr(0,7));
					Ext.getCmp("salesProgressEndMonth").getComponent('field-value').setData(curDate.substr(0,7));
					custom.salesProgressView(0);
				}
			},
			callCardRecord : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					var now = new Date();
					var curDate = '';
					var curMonth = parseInt(now.getMonth()+1);
				    curDate += now.getFullYear();
				    curDate += '-';
					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
					curDate += '-';
					curDate += now.getDate() < 10 ? '0'+now.getDate() : now.getDate();
					Ext.getCmp("callCardRecordBeginDate").getComponent('field-value').setHtml(curDate.substr(0,8)+"01");
					Ext.getCmp("callCardRecordBeginDate").getComponent('field-value').setData(curDate.substr(0,8)+"01");
					Ext.getCmp("callCardRecordEndDate").getComponent('field-value').setHtml(curDate);
					Ext.getCmp("callCardRecordEndDate").getComponent('field-value').setData(curDate);
					custom.callCardRecordView();
				}
			},
			orderRecord : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					var now = new Date();
					var curDate = '';
					var curMonth = parseInt(now.getMonth()+1);
				    curDate += now.getFullYear();
				    curDate += '-';
					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
					curDate += '-';
					curDate += now.getDate() < 10 ? '0'+now.getDate() : now.getDate();
					Ext.getCmp("orderRecordBeginDate").getComponent('field-value').setHtml(curDate.substr(0,8)+"01");
					Ext.getCmp("orderRecordBeginDate").getComponent('field-value').setData(curDate.substr(0,8)+"01");
					Ext.getCmp("orderRecordEndDate").getComponent('field-value').setHtml(curDate);
					Ext.getCmp("orderRecordEndDate").getComponent('field-value').setData(curDate);
					custom.orderRecordView(1);
				}
			},
			customerAddOrder : {
				tap : function(button, e, eOpts) {
					if(button.id == 'addOrder'){
						config.customer_code = button.getData();
						Ext.getCmp("titleBar").setActiveItem(1);
					}
					Ext.getCmp("customerHome").removeAll();
					Ext.getCmp("customerHome").add({
						xtype : 'customerSelectAddress'
					});
				}
			},
			customerSelectAddress : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					var CustomerCode = config.customer_code.replace("customer_button_","").split("_")[0];
					util.showLoadMask(null);
					var customerObj,customerAddressList;
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql(
				        		"select * from Customer where CustomerCode='"+CustomerCode+"' and SalesCode='"+config.current_user.user_name+"'", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				customerObj = r.rows.item(0);
				        			}
				        		},
				        		function (tx, e) {}
				            );
				            tx.executeSql(
				        		"select tmp.* from ( "+
								" select CustomerCode, '001' as IDCUSTSHPT, "+
								" rtrim(ltrim(Address1)) as Address1, rtrim(ltrim(Address2)) as Address2, rtrim(ltrim(Address3)) as Address3, '' as Address4 "+
								" from Customer where CustomerCode='"+CustomerCode+"' and SalesCode='"+config.current_user.user_name+"' "+
								" union all "+
								" select IDCUST as CustomerCode, IDCUSTSHPT, "+
								" rtrim(ltrim(TEXTSTRE1)) as Address1, rtrim(ltrim(TEXTSTRE2)) as Address2, rtrim(ltrim(TEXTSTRE3)) as Address3, rtrim(ltrim(TEXTSTRE4)) as Address4 "+
								" from CustomerAddress where IDCUST='"+CustomerCode+"' and SalesCode='"+config.current_user.user_name+"' "+
								" ) tmp order by tmp.CustomerCode, tmp.IDCUSTSHPT", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				customerAddressList = r.rows;
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
					setTimeout(function dataShow(){
						if(customerObj["AMTCRLIMT"]){
							config.customer_amtcrlimt = Number(customerObj["AMTCRLIMT"]);
						}else{
							config.customer_amtcrlimt = 0;
						}
						Ext.getCmp("customer-select-address-customer-name").setHtml(customerObj["CustomerCode"]+" "+customerObj["CustomerName"]);
						if(customerObj["Balance"]){
							Ext.getCmp("customer-select-address-customer-name").setData(customerObj["Balance"]+"");
							config.customer_balance = Number(customerObj["Balance"]);
						}else{
							Ext.getCmp("customer-select-address-customer-name").setData("0");
							config.customer_balance = 0;
						}
                		Ext.getCmp("customer-select-address-customer-name-item").setHtml(customerObj["CustomerCode"]+" "+customerObj["CustomerName"]);
                		Ext.getCmp("customer-select-address-customer-area-item").setHtml(config.area_code);
						if(customerAddressList  && Number(customerAddressList.length)>0){
							for(var i=0;i<customerAddressList.length;i++){
								if(i<Number(Number(customerAddressList.length)-1)){
                    				var customerAddressObj1 = customerAddressList.item(i);
                    				var customerAddressObj2 = customerAddressList.item(i+1);
                    				var num1 = (i+1);
                    				num1 = num1 < 10 ? '0'+num1 : num1;
                    				var num2 = (i+2);
                    				num2 = num2 < 10 ? '0'+num2 : num2;
                    				Ext.getCmp("address-list-data").add(
                        				{
                        					xtype : 'container',
                        					cls : 'customer-select-address-info',
                        					layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												cls : 'customer-select-address-button',
												html : num1+" "+customerAddressObj1["Address1"],
												data : customerAddressObj1["IDCUSTSHPT"]+" "+customerAddressObj1["Address1"]+" "+customerAddressObj1["Address2"]+" "+customerAddressObj1["Address3"]+" "+customerAddressObj1["Address4"],
												listeners : {
													element : 'element',
													singletap : function() {
														Ext.getCmp("customer-select-address-customer-address-item").setHtml("");
														Ext.getCmp("customer-select-address-customer-address-item").setHtml(this.getData());
													}
												}
											},{
												cls : 'customer-select-address-line'
											},{
												flex : 1,
												cls : 'customer-select-address-button',
												html : num2+" "+customerAddressObj2["Address1"],
												data : customerAddressObj2["IDCUSTSHPT"]+" "+customerAddressObj2["Address1"]+" "+customerAddressObj2["Address2"]+" "+customerAddressObj2["Address3"]+" "+customerAddressObj2["Address4"],
												listeners : {
													element : 'element',
													singletap : function() {
														Ext.getCmp("customer-select-address-customer-address-item").setHtml("");
														Ext.getCmp("customer-select-address-customer-address-item").setHtml(this.getData());
													}
												}
											}]
                        				}
                        			);
                    				i++;
                    			}else{
                    				var customerObjAddress = customerAddressList.item(i);
                    				var num = (i+1);
                    				num = num < 10 ? '0'+num : num;
                    				Ext.getCmp("address-list-data").add(
                        				{
                        					xtype : 'container',
                        					cls : 'customer-select-address-info',
                        					layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												cls : 'customer-select-address-button',
												html : num+" "+customerObjAddress["Address1"],
												data : customerObjAddress["IDCUSTSHPT"]+" "+customerObjAddress["Address1"]+" "+customerObjAddress["Address2"]+" "+customerObjAddress["Address3"]+" "+customerObjAddress["Address4"],
												listeners : {
													element : 'element',
													singletap : function() {
														Ext.getCmp("customer-select-address-customer-address-item").setHtml("");
														Ext.getCmp("customer-select-address-customer-address-item").setHtml(this.getData());
													}
												}
											},{
												cls : 'customer-select-address-line'
											},{
												flex : 1,
												cls : 'customer-select-address-button',
												html : ""
											}]
                        				}
                        			);
                    			}
                    		}
						}
						util.hideLoadMask();
					},1500);
                    var now = new Date();
					var curDate = '';
					var curMonth = parseInt(now.getMonth()+1);
				    curDate += now.getFullYear();
				    curDate += '-';
					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
					curDate += '-';
					curDate += now.getDate() < 10 ? '0'+now.getDate() : now.getDate();
					Ext.getCmp("orderDate").getComponent('field-value').setHtml(curDate);
					Ext.getCmp("orderDate").getComponent('field-value').setData(curDate);
					var dateDay = Date.parse(curDate);
					dateDay = dateDay+(2*24*60*60*1000);
					dateDay = new Date(dateDay)
					var curDate = '';
					var curMonth = parseInt(dateDay.getMonth()+1);
				    curDate += dateDay.getFullYear();
				    curDate += '-';
					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
					curDate += '-';
					curDate += dateDay.getDate() < 10 ? '0'+dateDay.getDate() : dateDay.getDate();
					Ext.getCmp("deliveryDate").getComponent('field-value').setHtml(curDate);
					Ext.getCmp("deliveryDate").getComponent('field-value').setData(curDate);
				}
			},
			confirmBuy : {
				tap : function(button, e, eOpts) {
					if(Ext.getCmp("customer-select-address-customer-address-item").getHtml()==""){
						util.showMessageMask('請選擇收貨地址','warn-max');
					}else{
						var PaymentMode = "",PaymentModeStr = "";
						if(Ext.getCmp('PaymentMode1').getSrc().indexOf('radio_checked.png')>-1){
							PaymentMode = 1;
							PaymentModeStr = '月結';
                    	}else if(Ext.getCmp('PaymentMode2').getSrc().indexOf('radio_checked.png')>-1){
                    		PaymentMode = 2;
							PaymentModeStr = '現款';
                    	}else if(Ext.getCmp('PaymentMode3').getSrc().indexOf('radio_checked.png')>-1){
                    		PaymentMode = 3;
							PaymentModeStr = '其他';
                    	}
                    	config.parameter = {};
						config.parameter = {
							CustomerCode : config.customer_code.replace("customer_button_","").split("_")[0],
							CustomerName : Ext.getCmp("customer-select-address-customer-name").getHtml(),
							Address : Ext.getCmp("customer-select-address-customer-address-item").getHtml(),
							OrderDate : Ext.getCmp("orderDate").getComponent('field-value').getHtml(),
							DeliveryDate : Ext.getCmp("deliveryDate").getComponent('field-value').getHtml(),
							balance : Ext.getCmp("customer-select-address-customer-name").getData(),
							PaymentMode : PaymentMode,
							PaymentModeStr : PaymentModeStr
						};
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'customerNewOrder'
						});
					}
				}
			},
			customerNewOrder : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					Ext.getCmp("customer-new-order-customer-name").setHtml(config.parameter.CustomerName);
					Ext.getCmp("customer-new-order-customer-name").setData(config.parameter.CustomerCode);
					Ext.getCmp("order-date").setHtml(config.parameter.OrderDate);
					Ext.getCmp("payment-mode").setHtml(config.parameter.PaymentModeStr);
					Ext.getCmp("delivery-date").setHtml(config.parameter.DeliveryDate);
					Ext.getCmp("balance").setHtml("$"+custom.thousandBitSeparator(config.parameter.balance,0));
					Ext.getCmp("delivery-address").setHtml(config.parameter.Address);
					if(config.order_item_arr == null){
						config.order_item_arr = [];
						var orderItemTable=document.getElementById('orderItem');
						var tr=orderItemTable.rows[0];
						config.order_item_arr.push(tr);
					}
				}
			},
			selectBrand : {
				tap : function(button, e, eOpts) {
					Ext.getCmp("customerHome").removeAll();
					Ext.getCmp("customerHome").add({
						xtype : 'newOrderSelectBrand'
					});
				}
			},
			selectCancel : {
				tap : function(button, e, eOpts) {
					Ext.getCmp("customerHome").removeAll();
					Ext.getCmp("customerHome").add({
						xtype : 'customerNewOrder'
					});
				}
			},
			newOrderSelectBrand : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					Ext.getCmp("customer-new-order-customer-name").setHtml(config.parameter.CustomerName);
					Ext.getCmp("order-date").setHtml(config.parameter.OrderDate);
					Ext.getCmp("payment-mode").setHtml(config.parameter.PaymentModeStr);
					Ext.getCmp("delivery-date").setHtml(config.parameter.DeliveryDate);
					Ext.getCmp("balance").setHtml("$"+custom.thousandBitSeparator(config.parameter.balance,0));
					Ext.getCmp("delivery-address").setHtml(config.parameter.Address);
					util.showLoadMask(null);
					var brandList;
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql(
				        		"select * from Brand where SalesCode='"+config.current_user.user_name+"' order by BrandName", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				brandList = r.rows;
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
					setTimeout(function dataShow(){
						if(brandList && Number(brandList.length)>0){
							for(var i=0;i<brandList.length;i++){
                    			if(i<Number(Number(brandList.length)-4)){
                    				var brandObj1 = brandList.item(i);
	                    			var brandObj2 = brandList.item(i+1);
	                    			var brandObj3 = brandList.item(i+2);
	                    			var brandObj4 = brandList.item(i+3);
	                    			var brandObj5 = brandList.item(i+4);
	                    			var ImgObj1 = new Image();
	                    			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG';
	                    			var ImgObj1IsExist = 0;
	                    			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
	                    				ImgObj1IsExist = 1;
	                    			}
	                    			var ImgObj2 = new Image();
	                    			ImgObj2.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG';
	                    			var ImgObj2IsExist = 0;
	                    			if (ImgObj2.fileSize > 0 || (ImgObj2.width > 0 && ImgObj2.height > 0)) {
	                    				ImgObj2IsExist = 1;
	                    			}
	                    			var ImgObj3 = new Image();
	                    			ImgObj3.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj3["BrandName"]+'.JPG';
	                    			var ImgObj3IsExist = 0;
	                    			if (ImgObj3.fileSize > 0 || (ImgObj3.width > 0 && ImgObj3.height > 0)) {
	                    				ImgObj3IsExist = 1;
	                    			}
	                    			var ImgObj4 = new Image();
	                    			ImgObj4.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj4["BrandName"]+'.JPG';
	                    			var ImgObj4IsExist = 0;
	                    			if (ImgObj4.fileSize > 0 || (ImgObj4.width > 0 && ImgObj4.height > 0)) {
	                    				ImgObj4IsExist = 1;
	                    			}
	                    			var ImgObj5 = new Image();
	                    			ImgObj5.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj5["BrandName"]+'.JPG';
	                    			var ImgObj5IsExist = 0;
	                    			if (ImgObj5.fileSize > 0 || (ImgObj5.width > 0 && ImgObj5.height > 0)) {
	                    				ImgObj5IsExist = 1;
	                    			}
                    				Ext.getCmp("brand-list-data").add(
                    					{
											xtype : 'container',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj1["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj1["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj2IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj2IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj2["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj2["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj3IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj3IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj3["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj3["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj3["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj4IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj4IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj4["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj4["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj4["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj5IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj5IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj5["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj5["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj5["BrandCode"]
												}]
											}]
										}
                    				);
                    				i=i+4;
                    			} else if(i<Number(Number(brandList.length)-3)){
                    				var brandObj1 = brandList.item(i);
	                    			var brandObj2 = brandList.item(i+1);
	                    			var brandObj3 = brandList.item(i+2);
	                    			var brandObj4 = brandList.item(i+3);
	                    			var ImgObj1 = new Image();
	                    			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG';
	                    			var ImgObj1IsExist = 0;
	                    			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
	                    				ImgObj1IsExist = 1;
	                    			}
	                    			var ImgObj2 = new Image();
	                    			ImgObj2.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG';
	                    			var ImgObj2IsExist = 0;
	                    			if (ImgObj2.fileSize > 0 || (ImgObj2.width > 0 && ImgObj2.height > 0)) {
	                    				ImgObj2IsExist = 1;
	                    			}
	                    			var ImgObj3 = new Image();
	                    			ImgObj3.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj3["BrandName"]+'.JPG';
	                    			var ImgObj3IsExist = 0;
	                    			if (ImgObj3.fileSize > 0 || (ImgObj3.width > 0 && ImgObj3.height > 0)) {
	                    				ImgObj3IsExist = 1;
	                    			}
	                    			var ImgObj4 = new Image();
	                    			ImgObj4.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj4["BrandName"]+'.JPG';
	                    			var ImgObj4IsExist = 0;
	                    			if (ImgObj4.fileSize > 0 || (ImgObj4.width > 0 && ImgObj4.height > 0)) {
	                    				ImgObj4IsExist = 1;
	                    			}
                    				Ext.getCmp("brand-list-data").add(
                    					{
											xtype : 'container',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj1["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj1["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj2IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj2IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj2["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj2["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj3IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj3IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj3["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj3["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj3["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj4IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj4IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj4["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj4["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj4["BrandCode"]
												}]
											},{
												flex : 1
											}]
										}
                    				);
                    				i=i+3;
                    			} else if(i<Number(Number(brandList.length)-2)){
                    				var brandObj1 = brandList.item(i);
	                    			var brandObj2 = brandList.item(i+1);
	                    			var brandObj3 = brandList.item(i+2);
	                    			var ImgObj1 = new Image();
	                    			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG';
	                    			var ImgObj1IsExist = 0;
	                    			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
	                    				ImgObj1IsExist = 1;
	                    			}
	                    			var ImgObj2 = new Image();
	                    			ImgObj2.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG';
	                    			var ImgObj2IsExist = 0;
	                    			if (ImgObj2.fileSize > 0 || (ImgObj2.width > 0 && ImgObj2.height > 0)) {
	                    				ImgObj2IsExist = 1;
	                    			}
	                    			var ImgObj3 = new Image();
	                    			ImgObj3.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj3["BrandName"]+'.JPG';
	                    			var ImgObj3IsExist = 0;
	                    			if (ImgObj3.fileSize > 0 || (ImgObj3.width > 0 && ImgObj3.height > 0)) {
	                    				ImgObj3IsExist = 1;
	                    			}
	                    			Ext.getCmp("brand-list-data").add(
                    					{
											xtype : 'container',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj1["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj1["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj2IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj2IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj2["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj2["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj3IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj3IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj3["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj3["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj3["BrandCode"]
												}]
											},{
												flex : 1
											},{
												flex : 1
											}]
										}
                    				);
                    				i=i+2;
                    			} else if(i<Number(Number(brandList.length)-1)){
                    				var brandObj1 = brandList.item(i);
	                    			var brandObj2 = brandList.item(i+1);
	                    			var ImgObj1 = new Image();
	                    			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG';
	                    			var ImgObj1IsExist = 0;
	                    			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
	                    				ImgObj1IsExist = 1;
	                    			}
	                    			var ImgObj2 = new Image();
	                    			ImgObj2.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG';
	                    			var ImgObj2IsExist = 0;
	                    			if (ImgObj2.fileSize > 0 || (ImgObj2.width > 0 && ImgObj2.height > 0)) {
	                    				ImgObj2IsExist = 1;
	                    			}
	                    			Ext.getCmp("brand-list-data").add(
                    					{
											xtype : 'container',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj1["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj1["BrandCode"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj2IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj2IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj2["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj2["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj2["BrandCode"]
												}]
											},{
												flex : 1
											},{
												flex : 1
											},{
												flex : 1
											}]
										}
                    				);
                    				i=i+1;
                    			} else {
                    				var brandObj1 = brandList.item(i);
                    				var ImgObj1 = new Image();
	                    			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG';
	                    			var ImgObj1IsExist = 0;
	                    			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
	                    				ImgObj1IsExist = 1;
	                    			}
                    				Ext.getCmp("brand-list-data").add(
                    					{
											xtype : 'container',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
													iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
													text : ''+brandObj1["BrandName"],
													icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj1["BrandName"]+'.JPG',
													action : 'brandTap',
													data : brandObj1["BrandCode"]
												}]
											},{
												flex : 1
											},{
												flex : 1
											},{
												flex : 1
											},{
												flex : 1
											}]
										}
                    				);
                    			}
                			}
						}
						util.hideLoadMask();
					},1500);
				}
			},
			brandTap : {
				tap : function(button, e, eOpts) {
					eval("config.parameter.BrandCode='"+button.getData()+"'");
					Ext.getCmp("customerHome").removeAll();
					Ext.getCmp("customerHome").add({
						xtype : 'newOrderSelectSort'
					});
				}
			},
			newOrderSelectSort : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					Ext.getCmp("customer-new-order-customer-name").setHtml(config.parameter.CustomerName);
					Ext.getCmp("order-date").setHtml(config.parameter.OrderDate);
					Ext.getCmp("payment-mode").setHtml(config.parameter.PaymentModeStr);
					Ext.getCmp("delivery-date").setHtml(config.parameter.DeliveryDate);
					Ext.getCmp("balance").setHtml("$"+custom.thousandBitSeparator(config.parameter.balance,0));
					Ext.getCmp("delivery-address").setHtml(config.parameter.Address);
					util.showLoadMask(null);
					var brandObj,optfld4List;
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql(
				        		"select * from Brand where SalesCode='"+config.current_user.user_name+"' and BrandCode='"+config.parameter.BrandCode+"'", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				brandObj = r.rows.item(0);
				        			}
				        		},
				        		function (tx, e) {}
				            );
				            tx.executeSql(
				        		"select aa.OPTFLD4 as OPTFLD4, aa.BrandName as BrandName from " +
								" (select b.BrandName, a.OPTFLD4 from Item a " +
								" left join Brand b on a.BrandID = b.BrandCode " +
								" where a.BrandID = '"+config.parameter.BrandCode+"' and b.SalesCode='"+config.current_user.user_name+"' and a.SalesCode='"+config.current_user.user_name+"' group by b.BrandName, a.OPTFLD4) aa " +
								" order by aa.OPTFLD4", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				optfld4List = r.rows;
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
					setTimeout(function dataShow(){
						eval("config.parameter.BrandName='"+brandObj["BrandName"]+"'");
						var ImgObj1 = new Image();
            			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj["BrandName"]+'.JPG';
            			var ImgObj1IsExist = 0;
            			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
            				ImgObj1IsExist = 1;
            			}
            			Ext.getCmp("select-list-data").add(
        					{
								xtype : 'container',
								layout : {
									type : 'hbox'
								},
								items : [{
									flex : 1,
									xtype : 'container',
									items : [{
										xtype : 'button',
										cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
										iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
										text : ''+brandObj["BrandName"],
										icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+brandObj["BrandName"]+'.JPG',
										action : 'selectBrand'
									}]
								},{
									flex : 1
								},{
									flex : 1
								},{
									flex : 1
								}]
							}
        				);
						if(optfld4List && Number(optfld4List.length)>0){
							for(var i=0;i<optfld4List.length;i++){
								if(i<Number(Number(optfld4List.length)-1)){
									var sortObj1 = optfld4List.item(i);
                    				var sortObj2 = optfld4List.item(i+1);
                    				Ext.getCmp("sort-list-data").add(
                    					{
											xtype : 'container',
											cls : 'sort-item-line',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												cls : 'sort-item-left',
												items : [{
													xtype : 'button',
													cls : 'sort-item-button',
													icon : ''+cordova.file.dataDirectory +'/Logo/Category/'+brandObj["BrandName"]+"_"+sortObj1["OPTFLD4"]+'.JPG',
													action : 'sortTap',
													html : sortObj1["OPTFLD4"],
													data : sortObj1["OPTFLD4"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : 'sort-item-button',
													icon : ''+cordova.file.dataDirectory +'/Logo/Category/'+brandObj["BrandName"]+"_"+sortObj2["OPTFLD4"]+'.JPG',
													action : 'sortTap',
													html : sortObj2["OPTFLD4"],
													data : sortObj2["OPTFLD4"]
												}]
											}]
										}
                    				);
                    				i=i+1;
								}else{
									var sortObj1 = optfld4List.item(i);
									Ext.getCmp("sort-list-data").add(
                    					{
											xtype : 'container',
											cls : 'sort-item-line',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												cls : 'sort-item-left',
												items : [{
													xtype : 'button',
													cls : 'sort-item-button',
													icon : ''+cordova.file.dataDirectory +'/Logo/Category/'+brandObj["BrandName"]+"_"+sortObj1["OPTFLD4"]+'.JPG',
													action : 'sortTap',
													html : sortObj1["OPTFLD4"],
													data : sortObj1["OPTFLD4"]
												}]
											},{
												flex : 1,
												xtype : 'container'
											}]
                    					}
                    				);
								}
                			}
						}
						util.hideLoadMask();
					},500);
				}
			},
			sortTap : {
				tap : function(button, e, eOpts) {
					eval("config.parameter.Optfld4='"+button.getData()+"'");
					Ext.getCmp("customerHome").removeAll();
					Ext.getCmp("customerHome").add({
						xtype : 'newOrderSelectType'
					});
				}
			},
			newOrderSelectType : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					Ext.getCmp("customer-new-order-customer-name").setHtml(config.parameter.CustomerName);
					Ext.getCmp("order-date").setHtml(config.parameter.OrderDate);
					Ext.getCmp("payment-mode").setHtml(config.parameter.PaymentModeStr);
					Ext.getCmp("delivery-date").setHtml(config.parameter.DeliveryDate);
					Ext.getCmp("balance").setHtml("$"+custom.thousandBitSeparator(config.parameter.balance,0));
					Ext.getCmp("delivery-address").setHtml(config.parameter.Address);
					util.showLoadMask(null);
					var typeList;
					config.database.transaction(
				        function (tx) {
				            tx.executeSql(
				        		"select optfld3 as OPTFLD3 from Item where BrandID='"+config.parameter.BrandCode+"' and OPTFLD4='"+config.parameter.Optfld4+"' " +
								" and SalesCode = '"+config.current_user.user_name+"' group by OPTFLD3", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				typeList = r.rows;
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
					setTimeout(function dataShow(){
						var ImgObj1 = new Image();
            			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+config.parameter.BrandName+'.JPG';
            			var ImgObj1IsExist = 0;
            			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
            				ImgObj1IsExist = 1;
            			}
						var ImgObj2 = new Image();
            			ImgObj2.src = ''+cordova.file.dataDirectory +'/Logo/Category/'+config.parameter.BrandName+"_"+config.parameter.Optfld4+'.JPG';
            			var ImgObj2IsExist = 0;
            			if (ImgObj2.fileSize > 0 || (ImgObj2.width > 0 && ImgObj2.height > 0)) {
            				ImgObj2IsExist = 1;
            			}
						Ext.getCmp("select-list-data").add(
        					{
								xtype : 'container',
								layout : {
									type : 'hbox'
								},
								items : [{
									flex : 1,
									xtype : 'container',
									items : [{
										xtype : 'button',
										cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
										iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
										text : ''+config.parameter.BrandName,
										icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+config.parameter.BrandName+'.JPG',
										action : 'selectBrand'
									}]
								},{
									flex : 1,
									xtype : 'container',
									items : [{
										xtype : 'button',
										cls : ImgObj2IsExist > 0 ? 'item-button-exist' : 'item-button',
										iconCls : ImgObj2IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
										text : ''+config.parameter.Optfld4,
										action : 'brandTap',
										icon : ''+cordova.file.dataDirectory +'/Logo/Category/'+config.parameter.BrandName+"_"+config.parameter.Optfld4+'.JPG',
										data : config.parameter.BrandCode
									}]
								},{
									flex : 1
								},{
									flex : 1
								}]
							}
        				);
        				if(typeList && Number(typeList.length)>0){
        					for(var i=0;i<typeList.length;i++){
								if(i<Number(Number(typeList.length)-1)){
									var typeObj1 = typeList.item(i);
	                				var typeObj2 = typeList.item(i+1);
	                				Ext.getCmp("type-list-data").add(
	                					{
											xtype : 'container',
											cls : 'sort-item-line',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												cls : 'sort-item-left',
												items : [{
													xtype : 'button',
													cls : 'sort-item-button',
													action : 'typeTap',
													html : typeObj1["OPTFLD3"],
													data : typeObj1["OPTFLD3"]
												}]
											},{
												flex : 1,
												xtype : 'container',
												items : [{
													xtype : 'button',
													cls : 'sort-item-button',
													action : 'typeTap',
													html : typeObj2["OPTFLD3"],
													data : typeObj2["OPTFLD3"]
												}]
											}]
										}
	                				);
	                				i=i+1;
								}else{
									var typeObj1 = typeList.item(i);
									Ext.getCmp("type-list-data").add(
	                					{
											xtype : 'container',
											cls : 'sort-item-line',
											layout : {
												type : 'hbox'
											},
											items : [{
												flex : 1,
												xtype : 'container',
												cls : 'sort-item-left',
												items : [{
													xtype : 'button',
													cls : 'sort-item-button',
													action : 'typeTap',
													html : typeObj1["OPTFLD3"],
													data : typeObj1["OPTFLD3"]
												}]
											},{
												flex : 1,
												xtype : 'container'
											}]
	                					}
	                				);
								}
	            			}
        				}
        				util.hideLoadMask();
					},1500);
				}
			},
			typeTap : {
				tap : function(button, e, eOpts) {
					eval("config.parameter.Optfld3='"+button.getData()+"'");
					Ext.getCmp("customerHome").removeAll();
					Ext.getCmp("customerHome").add({
						xtype : 'newOrderSelectProduct'
					});
				}
			},
			newOrderSelectProduct : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					Ext.getCmp("customer-new-order-customer-name").setHtml(config.parameter.CustomerName);
					Ext.getCmp("order-date").setHtml(config.parameter.OrderDate);
					Ext.getCmp("payment-mode").setHtml(config.parameter.PaymentModeStr);
					Ext.getCmp("delivery-date").setHtml(config.parameter.DeliveryDate);
					Ext.getCmp("balance").setHtml("$"+custom.thousandBitSeparator(config.parameter.balance,0));
					Ext.getCmp("delivery-address").setHtml(config.parameter.Address);
					util.showLoadMask(null);
					var productList;
					config.database.transaction(
				        function (tx) {
				            tx.executeSql(
				        		"select a.*,c.ItemName as ItemNameChinese,b.ItemShort as Short "+
								" from Item a "+
								" left join ItemShort b on a.ItemCode = b.ItemCode "+
								" left join ItemChinese c on a.ItemCode = c.ItemCode "+
								" where a.BrandID='"+config.parameter.BrandCode+"' "+
								" and a.OPTFLD4='"+config.parameter.Optfld4+"' "+
								" and a.OPTFLD3='"+config.parameter.Optfld3+"' "+
								" and a.SalesCode='"+config.current_user.user_name+"' "+
								" order by a.ItemCode", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				productList = r.rows;
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
					setTimeout(function dataShow(){
						var ImgObj1 = new Image();
            			ImgObj1.src = ''+cordova.file.dataDirectory +'/Logo/Brand/'+config.parameter.BrandName+'.JPG';
            			var ImgObj1IsExist = 0;
            			if (ImgObj1.fileSize > 0 || (ImgObj1.width > 0 && ImgObj1.height > 0)) {
            				ImgObj1IsExist = 1;
            			}
						var ImgObj2 = new Image();
            			ImgObj2.src = ''+cordova.file.dataDirectory +'/Logo/Category/'+config.parameter.BrandName+"_"+config.parameter.Optfld4+'.JPG';
            			var ImgObj2IsExist = 0;
            			if (ImgObj2.fileSize > 0 || (ImgObj2.width > 0 && ImgObj2.height > 0)) {
            				ImgObj2IsExist = 1;
            			}
						Ext.getCmp("select-list-data").add(
        					{
								xtype : 'container',
								layout : {
									type : 'hbox'
								},
								items : [{
									flex : 1,
									xtype : 'container',
									items : [{
										xtype : 'button',
										cls : ImgObj1IsExist > 0 ? 'item-button-exist' : 'item-button',
										iconCls : ImgObj1IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
										text : ''+config.parameter.BrandName,
										icon : ''+cordova.file.dataDirectory +'/Logo/Brand/'+config.parameter.BrandName+'.JPG',
										action : 'selectBrand'
									}]
								},{
									flex : 1,
									xtype : 'container',
									items : [{
										xtype : 'button',
										cls : ImgObj2IsExist > 0 ? 'item-button-exist' : 'item-button',
										iconCls : ImgObj2IsExist > 0 ? 'item-button-icon-exist' : 'item-button-icon',
										text : ''+config.parameter.Optfld4,
										icon : ''+cordova.file.dataDirectory +'/Logo/Category/'+config.parameter.BrandName+"_"+config.parameter.Optfld4+'.JPG',
										action : 'brandTap',
										data : config.parameter.BrandCode
									}]
								},{
									flex : 1,
									xtype : 'container',
									items : [{
										xtype : 'button',
										cls : 'item-button',
										action : 'sortTap',
										html : config.parameter.Optfld3,
										data : config.parameter.Optfld4
									}]
								},{
									flex : 1
								}]
							}
        				);
        				if(productList && Number(productList.length)>0){
        					for(var i=0;i<productList.length;i++){
	            				var productObj = productList.item(i);
	            				var htmlStr = "";
	            				if(productObj["ItemNameChinese"]){
	            					htmlStr += productObj["ItemNameChinese"];
	            				}else{
	            					htmlStr += productObj["ItemName"];
	            				}
	            				if(productObj["Short"]){
	            					htmlStr += "<br/>"+productObj["Short"];
	            				}
	            				Ext.getCmp("product-list-data").add(
	            					{
										xtype : 'container',
										cls : 'sort-item-line',
										layout : {
											type : 'hbox'
										},
										items : [{
											flex : 1,
											xtype : 'container',
											items : [{
												xtype : 'button',
												cls : 'sort-item-button',
												icon : ''+cordova.file.dataDirectory +'/Logo/Product/'+productObj["ItemCode"]+'.JPG',
												html : htmlStr,
												data : productObj["ItemCode"],
												action : 'productTap'
											}]
										}]
									}
	            				);
	            			}
        				}
        				util.hideLoadMask();
					},1500);
				}
			},
			productTap : {
				tap : function(button, e, eOpts) {
					eval("config.parameter.ItemCode='"+button.getData()+"'");
					Ext.getCmp("customerHome").removeAll();
					Ext.getCmp("customerHome").add({
						xtype : 'newOrderSelectProductInfo'
					});
				}
			},
			newOrderSelectProductInfo : {
				activate : function(newActiveItem, t, oldActiveItem, eOpts) {
					Ext.getCmp("customer-new-order-customer-name").setHtml(config.parameter.CustomerName);
					Ext.getCmp("order-date").setHtml(config.parameter.OrderDate);
					Ext.getCmp("payment-mode").setHtml(config.parameter.PaymentModeStr);
					Ext.getCmp("delivery-date").setHtml(config.parameter.DeliveryDate);
					Ext.getCmp("balance").setHtml("$"+custom.thousandBitSeparator(config.parameter.balance,0));
					Ext.getCmp("delivery-address").setHtml(config.parameter.Address);
					var now = new Date();
					var curDate = '';
					var curMonth = parseInt(now.getMonth()+1);
				    curDate += now.getFullYear();
				    curDate += '-';
					curDate += curMonth < 10 ? '0'+curMonth : curMonth;
					curDate += '-';
					curDate += now.getDate() < 10 ? '0'+now.getDate() : now.getDate();
					Ext.getCmp("callCardEndDate").getComponent('field-value').setHtml(curDate);
					Ext.getCmp("callCardEndDate").getComponent('field-value').setData(curDate);
					custom.callCardView();
					Ext.getCmp("cancelButton").setData(config.parameter.Optfld3);
				}
			},
			confirmButton : {
				tap : function(button, e, eOpts) {
					if(!Number(document.getElementById("orderNum").value)){
						util.showMessageMask('請輸入訂貨數量','warn-max');
					}else{
						var itemCode = Ext.getCmp("itemCode").getHtml();
						var productName = Ext.getCmp("productName").getHtml();
						var unit = Ext.getCmp("unit").getHtml();
						var orderNum = document.getElementById("orderNum").value;
						var unitPrice = Ext.getCmp("unitPrice").getData();
						var itemTotal = Ext.getCmp("itemTotal").getHtml();
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'customerNewOrder'
						});
						var trObj=config.order_item_arr[0];
						if(trObj){
							if(trObj.cells[1].innerHTML=='&nbsp;' || trObj.cells[1].innerHTML=='' ){
								config.order_item_arr.shift();
								var orderItemTable=document.getElementById('orderItem');
								orderItemTable.deleteRow(0);
							}else{
								var orderItemTable=document.getElementById('orderItem');
								orderItemTable.deleteRow(0);
								for(var i=0;i<config.order_item_arr.length;i++){
									var trObj=config.order_item_arr[i];
									var tr=orderItemTable.insertRow(i);
									if(Number(i)%2==0){
										tr.setAttribute("style", "height:2rem;background-color:#FFFFFF;");
									}else{
										tr.setAttribute("style", "height:2rem;background-color:#F5F5F5;");
									}
									tr.setAttribute("id", "item"+i);
									var td0=tr.insertCell(0);
									var td1=tr.insertCell(1);
									var td2=tr.insertCell(2);
									var td3=tr.insertCell(3);
									var td4=tr.insertCell(4);
									var td5=tr.insertCell(5);
									var td6=tr.insertCell(6);
									td0.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:16%;");
									td1.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:30%;");
									td2.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:8%;");
									td3.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:12%;");
									td4.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:10%;");
									td5.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:17%;");
									td6.setAttribute("style", "width:6%;");
									td0.innerHTML = trObj.cells[0].innerHTML;
									td1.innerHTML = trObj.cells[1].innerHTML;
									td2.innerHTML = trObj.cells[2].innerHTML;
									td3.innerHTML = trObj.cells[3].innerHTML;
									td4.innerHTML = trObj.cells[4].innerHTML;
									td5.innerHTML = trObj.cells[5].innerHTML;
									td6.innerHTML = trObj.cells[6].innerHTML;
								}
							}
						}else{
							var orderItemTable=document.getElementById('orderItem');
							orderItemTable.deleteRow(0);
						}
						var orderItemTable=document.getElementById('orderItem');
						var ItemtTrIdNumber = orderItemTable.rows.length;
						var tr=orderItemTable.insertRow(ItemtTrIdNumber);
						if(Number(ItemtTrIdNumber)%2==0){
							tr.setAttribute("style", "height:2rem;background-color:#FFFFFF;");
						}else{
							tr.setAttribute("style", "height:2rem;background-color:#F5F5F5;");
						}
						tr.setAttribute("id", "item"+ItemtTrIdNumber);
						var td0=tr.insertCell(0);
						var td1=tr.insertCell(1);
						var td2=tr.insertCell(2);
						var td3=tr.insertCell(3);
						var td4=tr.insertCell(4);
						var td5=tr.insertCell(5);
						var td6=tr.insertCell(6);
						td0.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:16%;");
						td1.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:30%;");
						td2.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:8%;");
						td3.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:12%;");
						td4.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:10%;");
						td5.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:17%;");
						td6.setAttribute("style", "width:6%;");
						td0.innerHTML = '<input style="border-radius:3px;text-align:center;border:1px solid #888888;height:1.6rem;width:2.8rem;" onkeyup="javascript:custom.onkeyupNumber(\'itemId'+ItemtTrIdNumber+'\')" onblur="javascript:custom.onchangeItemCode(\'itemId'+ItemtTrIdNumber+'\')" type="text" id="itemId'+ItemtTrIdNumber+'" name="itemId" value="'+itemCode+'" />';
						td1.innerHTML = productName;
						td2.innerHTML = unit;
						td3.innerHTML = '<input style="border-radius:3px;text-align:center;border:1px solid #888888;height:1.6rem;width:2rem;" onkeyup="javascript:custom.onkeyupOrderNumber(\'itemNum'+ItemtTrIdNumber+'\')" onblur="javascript:custom.onkeyupOrderNumber(\'itemNum'+ItemtTrIdNumber+'\')" type="text" id="itemNum'+ItemtTrIdNumber+'" name="itemNum" value="'+orderNum+'" />';
						td4.innerHTML = "$"+custom.thousandBitSeparator(unitPrice,2);
						td5.innerHTML = "$"+itemTotal;
						td6.innerHTML = '<img width="16px" src="./resources/images/icon_delete_default.png" onclick="custom.deleteOrderItemRow('+ItemtTrIdNumber+')">';
						config.order_item_arr.push(tr);
						
						var orderItemTable=document.getElementById('orderItem');
						var tr=orderItemTable.rows[ItemtTrIdNumber];
						var sumTotal = 0;
						for(var i=0 ; i < orderItemTable.rows.length; i++){
							sumTotal = Number(Number(sumTotal) + Number(orderItemTable.rows[i].cells[5].innerHTML.replace("$","").replace(",","")));
						}
						Ext.getCmp("orderTotal").setHtml("$"+custom.thousandBitSeparator(sumTotal,0));
					}
				}
			},
			customerUpdateOrder : {
				tap : function(button, e, eOpts) {
					config.parameter = {};
					var CustomerCode = Ext.getCmp("CustomerCode").getHtml();
					util.showLoadMask(null);
					var customerObj;
					config.database.transaction(
				        function (tx) {
				        	tx.executeSql(
				        		"select * from Customer where CustomerCode='"+CustomerCode+"' and SalesCode='"+config.current_user.user_name+"'", 
				        		[],
				        		function (tx, r) {
				        			if(Number(r.rows.length) > 0){
				        				customerObj = r.rows.item(0);
				        			}
				        		},
				        		function (tx, e) {}
				            );
				        }
				    );
					setTimeout(function dataShow(){
						if(customerObj["AMTCRLIMT"]){
							config.customer_amtcrlimt = Number(customerObj["AMTCRLIMT"]);
						}else{
							config.customer_amtcrlimt = 0;
						}
						if(customerObj && customerObj["Balance"] && Number(customerObj["Balance"])>0){
                			eval("config.parameter.balance='"+customerObj["Balance"]+"'");
                			config.customer_balance = Number(customerObj["Balance"]);
                		}else{
                			eval("config.parameter.balance='0'");
                			config.customer_balance = 0;
                		}
                		eval("config.parameter.CustomerName='"+Ext.getCmp("CustomerCode").getHtml() +" "+ Ext.getCmp("CustomerName").getHtml()+"'");
                		eval("config.parameter.CustomerCode='"+Ext.getCmp("CustomerCode").getHtml()+"'");
						eval("config.parameter.OrderDate='"+Ext.getCmp("OrderDateStr").getHtml()+"'");
						eval("config.parameter.PaymentModeStr='"+Ext.getCmp("PaymentStr").getHtml()+"'");
						eval("config.parameter.DeliveryDate='"+Ext.getCmp("DeliveryDateStr").getHtml()+"'");
						eval("config.parameter.Address='"+Ext.getCmp("Address").getHtml()+"'");
						eval("config.parameter.OrderNo='"+Ext.getCmp("OrderNo").getHtml()+"'");
						
						Ext.getCmp("titleBar").setActiveItem(1);
						Ext.getCmp("customerHome").removeAll();
						Ext.getCmp("customerHome").add({
							xtype : 'customerNewOrder'
						});
						config.order_item_arr.shift();
						var orderItemTable=document.getElementById('orderItem');
						orderItemTable.deleteRow(0);
						var orderDetailTable=document.getElementById('orderDetail');
						for(var i=0;i<orderDetailTable.rows.length;i++){
							var orderDetailTr = orderDetailTable.rows[i];
							var orderItemTable=document.getElementById('orderItem');
							var ItemtTrIdNumber = orderItemTable.rows.length;
							var tr=orderItemTable.insertRow(ItemtTrIdNumber);
							if(Number(ItemtTrIdNumber)%2==0){
								tr.setAttribute("style", "height:2rem;background-color:#FFFFFF;");
							}else{
								tr.setAttribute("style", "height:2rem;background-color:#F5F5F5;");
							}
							tr.setAttribute("id", "item"+ItemtTrIdNumber);
							var td0=tr.insertCell(0);
							var td1=tr.insertCell(1);
							var td2=tr.insertCell(2);
							var td3=tr.insertCell(3);
							var td4=tr.insertCell(4);
							var td5=tr.insertCell(5);
							var td6=tr.insertCell(6);
							td0.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:16%;");
							td1.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:30%;");
							td2.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:8%;");
							td3.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:12%;");
							td4.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:10%;");
							td5.setAttribute("style", "border-right:1px solid #CFCFCF;padding-left:0.1rem;width:17%;");
							td6.setAttribute("style", "width:6%;");
							
							td0.innerHTML = '<input style="border-radius:3px;text-align:center;border:1px solid #888888;height:1.6rem;width:2.8rem;" onkeyup="javascript:custom.onkeyupNumber(\'itemId'+ItemtTrIdNumber+'\')" onblur="javascript:custom.onchangeItemCode(\'itemId'+ItemtTrIdNumber+'\')" type="text" id="itemId'+ItemtTrIdNumber+'" name="itemId" value="'+orderDetailTr.cells[1].innerHTML+'" />';
							td1.innerHTML = orderDetailTr.cells[2].innerHTML;
							td2.innerHTML = orderDetailTr.cells[3].innerHTML;
							td3.innerHTML = '<input style="border-radius:3px;text-align:center;border:1px solid #888888;height:1.6rem;width:2rem;" onkeyup="javascript:custom.onkeyupOrderNumber(\'itemNum'+ItemtTrIdNumber+'\')" onblur="javascript:custom.onkeyupOrderNumber(\'itemNum'+ItemtTrIdNumber+'\')" type="text" id="itemNum'+ItemtTrIdNumber+'" name="itemNum" value="'+orderDetailTr.cells[4].innerHTML+'" />';
							td4.innerHTML = "$"+orderDetailTr.cells[5].innerHTML;
							td5.innerHTML = "$"+orderDetailTr.cells[6].innerHTML;
							td6.innerHTML = '<img width="16px" src="./resources/images/icon_delete_default.png" onclick="custom.deleteOrderItemRow('+ItemtTrIdNumber+')">';
							config.order_item_arr.push(tr);
						}
						var orderItemTable=document.getElementById('orderItem');
						var tr=orderItemTable.rows[ItemtTrIdNumber];
						var sumTotal = 0;
						for(var i=0 ; i < orderItemTable.rows.length; i++){
							sumTotal = Number(Number(sumTotal) + Number(orderItemTable.rows[i].cells[5].innerHTML.replace("$","").replace(",","")));
						}
						Ext.getCmp("orderTotal").setHtml("$"+custom.thousandBitSeparator(sumTotal,0));
						util.hideLoadMask();
					},1500);
				}
			},
			customerDeleteOrder : {
				tap : function(button, e, eOpts) {
					navigator.notification.confirm(
						'確定要刪除嗎？',
						function(btnId){
							if(btnId==2){
								var OrderNo = Ext.getCmp("OrderNo").getHtml();
								config.database.transaction(
						            function (tx) {
						                tx.executeSql("delete from OrderHead where SalesCode='"+config.current_user.user_name+"' and OrderNo="+OrderNo, [],
						                    function (tx, result) {
						                    	tx.executeSql("delete from OrderDetail where SalesCode='"+config.current_user.user_name+"' and OrderNo="+OrderNo);
						                    	util.showMessageMask('訂單刪除成功','success-max');
				                        		Ext.getCmp("orderHome").removeAll();
												Ext.getCmp("orderHome").add({
													xtype : 'orderList'
												});
						                    },
						                    function (tx, error) {
						                    	util.showMessageMask('訂單刪除失敗','error-max');
						                    }
						                );
						            }
						        );
							}
				        }, '溫馨提示', ['取消','確定']
					);
				}
			},
			orderSettleAction : {
				tap : function(button, e, eOpts) {
					var TotalAmountNumber = Number(Ext.getCmp("orderTotal").getHtml().replace("$","").replace(",",""));
					if(Number(config.customer_balance) < TotalAmountNumber){
						navigator.notification.confirm(
							'此客戶超過貸額：'+custom.thousandBitSeparator(config.customer_amtcrlimt,0)+'，今次為$'+custom.thousandBitSeparator(TotalAmountNumber,0),
							function(btnId){
								if(btnId==2){
									custom.orderSettle();
								}
					        }, '溫馨提示', ['取消','確定']
						);
					}else{
						custom.orderSettle();
					}
				}
			}
		}
	}
});